import React, { useEffect, useState } from 'react'
import { ToastAndroid, FlatList, StyleSheet, TouchableOpacity, Text, Button, View, Image, ImageBackground, ScrollView, Dimensions } from 'react-native';
import { AntDesign } from '@expo/vector-icons';
import { Entypo } from '@expo/vector-icons';
import { useAuth, baseURL } from '../../context/AuthProvider';
import axios from '../../api/axios';
import { Toast } from 'antd-mobile-rn';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useFocusEffect } from '@react-navigation/native';
const Btn = ({ style, children, ...rest }) => {
    return <TouchableOpacity {...rest}
        style={{ borderRadius: 10, justifyContent: 'center', alignItems: 'center', ...style }}>
        <Text style={{ color: 'white' }}>{children}</Text>
    </TouchableOpacity>
}
const add = (m) => { return m < 10 ? + m : m }
const fortime = (shijianchuo) => {
    var time = new Date(shijianchuo);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    return y + '-' + add(m) + '-' + add(d);
}
const screenW = Dimensions.get('window').width;
const screenH = Dimensions.get('window').height;
const PotDetail = ({ navigation, route }) => {
    const { user, setUser, delUser } = useAuth()

    const potid = route.params.potid;
    const sum = route.params.sum;
    const [pot, setPot] = useState({});
    const [w, setW] = useState('100%')
    const [h, setH] = useState('100%')
    const [text, setText] = useState('')
    const [eff, setEff] = useState(0)

    const getimgW = (imageUri) => {
        Image.getSize(imageUri, (width, height) => {
            setW(screenW * 0.35)
            setH((height * screenW * 0.35) / width)
            return {
                width: screenW * 0.45,
                height: (height * screenW * 0.45) / width,
                resizeMode: 'contain'
            }
        })
    }
    useEffect(() => {
        console.log(potid,user.userid);
        axios.post('/flowerpot/getsingle1', { userid: user.userid, potid: potid }).then(res => {
            console.log(125781);
            console.log(res.data);
            setPot(res.data[0])
            setText(res.text)
        })
    }, [])
    const exchange = () => {
        // setEff(eff+1)
        let date = new Date()

        //获取当前时间，格式类似'2023-02-23 15:58:05'
        let year = date.getFullYear()
        let month = (date.getMonth() + 1).toString().padStart(2,'0')
        let day = date.getDate().toString().padStart(2,'0')
        let str = `${year}-${month}-${day}`
        if (sum >= 200) {
            axios.post('/flowerpot/exchange', { userid: user.userid, potid: potid, date: str }).then(res => {
                if(res.code == 200){
                    alert("兑换成功")
                    setText(()=>{
                        return "立即使用"
                    })
                }
            })
        } else{
            alert("硬币不足哦")
        }
    }
    // useFocusEffect(React.useCallback(() => {
        
    // }, []))
    const usepot = () => {
        // setEff(eff+1)
        axios.post('/flowerpot/usepot', {userid: user.userid, potid: potid}).then(res=>{
            if(res.code == 200){
                axios.post('/users/getmyuser', { userid: user.userid }).then(res => {
                    if (res.code == 200) {
                      console.log(5678);
                      console.log(res.data[0]);
                      setUser(res.data[0]);
                      AsyncStorage.setItem('user', JSON.stringify(res.data[0]), function (err) {
                        if (err) {
                            ToastAndroid.show("更换失败", 2000);

                        } else {
                            ToastAndroid.show("更换成功", 2000);
                        }
                      })
                      console.log(99999);
                    }
                  })
            }
        })
    }
    return (
        <View style={{ width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center' }}>

            <View style={{ width: '100%', backgroundColor: '#fff', height: '35%', alignItems: 'center', justifyContent: 'center' }}>
                <Image source={{ uri: pot.potimg ? baseURL + pot.potimg : '' }} style={[{ width: w, height: h, resizeMode: 'contain', bottom: 20 }, getimgW(baseURL + pot.potimg)]}></Image>
            </View>

            <View style={{ width: '100%', height: '65%', alignItems: 'center' }}>
                <View style={{ backgroundColor: '#fff', borderRadius: 10, width: '90%', height: '90%', borderColor: '#bbb', borderWidth: 1, marginTop: -25 }}>
                    <Text style={styles.title}>文字介绍</Text>
                    <Text style={styles.desc}>{pot.potname}</Text>
                    <Text style={styles.title}>花盆兑换规则</Text>
                    <Text style={styles.desc}>200硬币兑换</Text>
                    <Text style={styles.title}>花盆有效期</Text>
                    <Text style={styles.desc}>永久</Text>
                    <View style={{ alignItems: 'center', marginTop: '15%' }}>
                        <Btn onPress={text=="立即兑换"?exchange:usepot} style={{ backgroundColor: '#FF6450', width: '60%', padding: 4 }}>{text}</Btn>
                    </View>
                </View>
            </View>
        </View>
    )
}
const styles = StyleSheet.create({
    title: {
        fontSize: 16,
        margin: '3%'
    },
    desc: {
        fontSize: 13,
        margin: '3%',
        color: '#6D6C6C'
    }
});
export default PotDetail